﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ImageUtils
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 预览水印效果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton_Viewer_Click(object sender, EventArgs e)
        {
            // Load and watermark the image
            string originalImagePath = uiTextBox_InFolder.Text; // Replace with your image path
            List<string> files = new List<string>();

            //files = Directory.EnumerateFiles(originalImagePath, "*.*", SearchOption.TopDirectoryOnly)
            //                 .Where(f => Path.GetExtension(f).Equals(".jpg", StringComparison.OrdinalIgnoreCase) ||
            //                             Path.GetExtension(f).Equals(".jpeg", StringComparison.OrdinalIgnoreCase) ||
            //                             Path.GetExtension(f).Equals(".png", StringComparison.OrdinalIgnoreCase))
            //                 .ToArray().ToList();
            files = GetImageFiles(originalImagePath);
            files.Capacity = files.Count;
            if (files.Count > 0)
            {
                ImageAdd(files[0], false, uiRichTextBox_time.Text.Split(';')[2].Trim());
            }

        }

        private void uiButton_Select_Infolder_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                // Optionally set properties on folderBrowserDialog here

                // Show the dialog and check if user clicked OK
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    // Update the label with the selected folder path
                    uiTextBox_InFolder.Text = folderBrowserDialog.SelectedPath;
                }
            }
        }

        private void uiButton_Select_Outfolder_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                // Optionally set properties on folderBrowserDialog here

                // Show the dialog and check if user clicked OK
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    // Update the label with the selected folder path
                    uiTextBox_OutFolder.Text = folderBrowserDialog.SelectedPath;
                }
            }
        }



        //private bool ImageAdd(string imagePath,bool save,string timetext)
        //{
        //    Image originalImage = null;
        //    try
        //    {
        //        originalImage = Image.FromFile(imagePath);
        //        Bitmap bmp = new Bitmap(originalImage);
        //        using (Graphics g = Graphics.FromImage(bmp))
        //        {
        //            /**
        //             * 统一以bmp.Heigth，图片的左下角为换算基准
        //             */
        //            Font time_font = new Font("Arial", bmp.Height*0.06f, FontStyle.Bold);
        //            Font font = new Font("Arial", bmp.Height * 0.03f, FontStyle.Bold);
        //            SolidBrush brush = new SolidBrush(Color.FromArgb(255, Color.White));
        //            Pen linePen = new Pen(Color.Gold, font.Height*0.2f); // 黄色线条
        //            /**
        //             * 时间
        //             */
        //            SizeF textSize = g.MeasureString(timetext, time_font);
        //            PointF location = new PointF(bmp.Height/100, 
        //                bmp.Height - textSize.Height - font.Height*2f);

        //            // 绘制黄色竖线
        //            float lineX = location.X + textSize.Width;
        //            float lineHeight = textSize.Height; // 线条高度比文本稍长一些

        //            //string watermarkText = time_text + "\n沛县·紧鞍路\n2024-11-27\n星期三 晴 8°C";

        //            // 测量文本尺寸以确定位置

        //            g.DrawString(timetext, time_font, brush, location);
        //            //绘制黄色竖线
        //            //UIMessageBox.Show((location.Y).ToString() + ";" + (timetext.Length).ToString());
        //            g.DrawLine(linePen, lineX, bmp.Height-bmp.Height*0.25f, lineX, bmp.Height - bmp.Height * 0.12f);


        //            //定位位置
        //            PointF GpsLocation = new PointF(location.X, bmp.Height - bmp.Height * 0.12f);
        //            g.DrawString(uiTextBox_GPS.Text, font, brush, GpsLocation);
        //            //日期位置
        //            PointF DateLocation = new PointF(lineX, bmp.Height - bmp.Height * 0.25f);
        //            g.DrawString(uiTextBox_Date.Text + "\n" + "星期" + uiComboBox_Select.Text + "  " + uiTextBox_Weather.Text, font, brush, DateLocation);
        //            // Assign the watermarked image to PictureBox


        //            string todaytext = "今日水印";
        //            PointF todayLocation = new PointF(bmp.Width - bmp.Width * 0.1f, bmp.Height - bmp.Height * 0.08f);
        //            Font SimHeifont = new Font("SimHei", 66);
        //            g.DrawString(todaytext, SimHeifont, brush, todayLocation);
        //            //相机
        //            string camera = "相机";
        //            Font camerafont = new Font("SimHei", 46);
        //            PointF cameraLocation = new PointF(todayLocation.X, todayLocation.Y + 100);
        //            g.DrawString(camera, camerafont, brush, cameraLocation);
        //            //真实可验
        //            SolidBrush brushtrue = new SolidBrush(Color.FromArgb(255, Color.Black));
        //            PointF trueLocation = new PointF(cameraLocation.X + 120, cameraLocation.Y);
        //            Pen p = new Pen(Color.FromArgb(255, Color.Black));
        //            SolidBrush FillRectangle = new SolidBrush(Color.FromArgb(150, Color.AliceBlue));
        //            g.FillRectangle(FillRectangle, new Rectangle((int)trueLocation.X + 15, (int)trueLocation.Y, 250, 60));
        //            g.DrawString("真实可验", camerafont, brushtrue, trueLocation);
        //            string a = "防伪  YKAAYBRGNNNKXC";
        //            PointF aLocation = new PointF(cameraLocation.X - a.Length, cameraLocation.Y + 60);
        //            Font afont = new Font("SimHei", camerafont.Height * 0.4f);
        //            g.DrawString(a, afont, brush, aLocation);


        //            if (save)
        //            {


        //                string filename = Path.GetFileName(imagePath);
        //                bmp.Save(uiTextBox_OutFolder.Text + "\\" + filename);
        //            }
        //            else 
        //            {

        //                imageBox_Viewer.Image = bmp;
        //            }
        //            // Keep the reference to the bitmap
        //        }
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show($"Error loading or processing image: {ex.Message}");
        //        return false;
        //    }
        //    finally
        //    {
        //        if (originalImage != null && imageBox_Viewer.Image != originalImage)
        //        {
        //            originalImage.Dispose();
        //        }
        //    }
        //}


        private bool ImageAdd(string imagePath, bool save, string timetext)
        {
            Image originalImage = null;
            try
            {
                originalImage = Image.FromFile(imagePath);
                Bitmap bmp = new Bitmap(originalImage);
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    /**
                     * 统一以bmp.Heigth，图片的左下角为换算基准
                     */
                    Font time_font = new Font("Arial", bmp.Height * 0.06f, FontStyle.Bold);
                    Font font = new Font("Arial", bmp.Height * 0.03f, FontStyle.Bold);
                    SolidBrush brush = new SolidBrush(Color.FromArgb(255, Color.White));
                    Pen linePen = new Pen(Color.Gold, font.Height * 0.2f); // 黄色线条
                    /**
                     * 时间
                     */
                    SizeF textSize = g.MeasureString(timetext, time_font);
                    PointF location = new PointF(bmp.Height / 100,
                        bmp.Height - textSize.Height - font.Height * 2f);

                    // 绘制黄色竖线
                    float lineX = location.X + textSize.Width;
                    float lineHeight = textSize.Height; // 线条高度比文本稍长一些

                    //string watermarkText = time_text + "\n沛县·紧鞍路\n2024-11-27\n星期三 晴 8°C";

                    // 测量文本尺寸以确定位置

                    g.DrawString(timetext, time_font, brush, location);
                    //绘制黄色竖线
                    //UIMessageBox.Show((location.Y).ToString() + ";" + (timetext.Length).ToString());
                    g.DrawLine(linePen, lineX, bmp.Height - bmp.Height * 0.25f, lineX, bmp.Height - bmp.Height * 0.12f);


                    //定位位置
                    PointF GpsLocation = new PointF(location.X, bmp.Height - bmp.Height * 0.12f);
                    g.DrawString(uiTextBox_GPS.Text, font, brush, GpsLocation);
                    //日期位置
                    PointF DateLocation = new PointF(lineX, bmp.Height - bmp.Height * 0.25f);
                    g.DrawString(uiTextBox_Date.Text + "\n" + "星期" + uiComboBox_Select.Text + "  " + uiTextBox_Weather.Text, font, brush, DateLocation);
                    // Assign the watermarked image to PictureBox


                    string todaytext = "今日水印";
                    PointF todayLocation = new PointF(bmp.Width - bmp.Width * 0.1f, bmp.Height - bmp.Height * 0.08f);
                    Font SimHeifont = new Font("SimHei", 66);
                    g.DrawString(todaytext, SimHeifont, brush, todayLocation);
                    //相机
                    string camera = "相机";
                    Font camerafont = new Font("SimHei", 46);
                    PointF cameraLocation = new PointF(todayLocation.X, todayLocation.Y + 100);
                    g.DrawString(camera, camerafont, brush, cameraLocation);
                    //真实可验
                    SolidBrush brushtrue = new SolidBrush(Color.FromArgb(255, Color.Black));
                    PointF trueLocation = new PointF(cameraLocation.X + 120, cameraLocation.Y);
                    Pen p = new Pen(Color.FromArgb(255, Color.Black));
                    SolidBrush FillRectangle = new SolidBrush(Color.FromArgb(150, Color.AliceBlue));
                    g.FillRectangle(FillRectangle, new Rectangle((int)trueLocation.X + 15, (int)trueLocation.Y, 250, 60));
                    g.DrawString("真实可验", camerafont, brushtrue, trueLocation);
                    string a = "防伪  YKAAYBRGNNNKXC";
                    PointF aLocation = new PointF(cameraLocation.X - a.Length, cameraLocation.Y + 60);
                    Font afont = new Font("SimHei", camerafont.Height * 0.4f);
                    g.DrawString(a, afont, brush, aLocation);


                    if (save)
                    {


                        string filename = Path.GetFileName(imagePath);
                        bmp.Save(uiTextBox_OutFolder.Text + "\\" + filename);
                    }
                    else
                    {

                        imageBox_Viewer.Image = bmp;
                    }
                    // Keep the reference to the bitmap
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error loading or processing image: {ex.Message}");
                return false;
            }
            finally
            {
                if (originalImage != null && imageBox_Viewer.Image != originalImage)
                {
                    originalImage.Dispose();
                }
            }
        }



        private void uiButton_All_Click(object sender, EventArgs e)
        {
            if (uiTextBox_InFolder.Text.Length > 0 && uiTextBox_OutFolder.Text.Length > 0)
            {
                List<string> files = new List<string>();
                if (uiTextBox_InFolder.Text.Length > 0) {
                    files = GetImageFiles(uiTextBox_InFolder.Text);
                }
                if (files.Count > 0)
                {
                    List<string> strings = new List<string>();
                    strings = uiRichTextBox_time.Text.Split(';').ToList();
                    for (int i = 0; i < files.Count; i++)
                    {
                        if (files.Count == strings.Count)
                        {
                            ImageAdd(files[i], true, strings[i]);
                        }
                    }
                    UIMessageBox.ShowSuccess("处理结束");
                }
                
            }
        }
        private List<string> GetImageFiles(string folder)
        {
            return Directory.EnumerateFiles(folder, "*.*", SearchOption.TopDirectoryOnly)
                .Where(f => new[] { ".jpg", ".jpeg", ".png" }
                .Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase))
                .ToList();
        }

    }

    /**
     * 绘制工具类
     */
    public class DrawUtils
    {
        public void DrawLocal(Image image,string text)
        {
            try
            {
                using (Graphics g = Graphics.FromImage(image))
                {
                    /**
                     * 统一以bmp.Heigth，图片的左下角为换算基准
                     */
                    Font time_font = new Font("Arial", image.Height * 0.06f, FontStyle.Bold);
                    Font font = new Font("Arial", image.Height * 0.03f, FontStyle.Bold);
                    SolidBrush brush = new SolidBrush(Color.FromArgb(255, Color.White));
                    PointF location = new PointF(image.Height / 100,image.Height);
                    //定位位置
                    PointF GpsLocation = new PointF(location.X, image.Height - image.Height * 0.12f);
                    g.DrawString(text, font, brush, GpsLocation);
                }
            }
            catch
            {

            }
            
        }
    }
}
